package com.espirit.common;

import java.io.File;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.googlecode.cswish.Config;
import com.googlecode.cswish.struts.spring.GenericService;
import com.googlecode.cswish.util.Functions;

@Service
public class UploadFileService {
	
	private final static Logger logger = Logger.getLogger(UploadFileService.class);
	
	@Resource
	private Config config;
	
	@Resource
	private Functions functions;
	
	@Resource
	private GenericService genericService;

	
	public void setFiles(Class clazz , List<RelatedFile> files ,String identify) {
		if (files == null || files.isEmpty() || clazz == null) return ;
		for(RelatedFile file : files){
			setFile(clazz, file ,identify);
		}
	}
	
	public void setFile(Class clazz , RelatedFile model ,String identity ) {
		if (model == null || clazz == null) return ;
		if (model.getFile() != null) {
			// TODO: try to remove the old file	
			boolean removeOldFile = true;
			if (removeOldFile && model.getId() != null) {
				RelatedFile oldRelatedFile = genericService.load(model);
				if (oldRelatedFile != null && oldRelatedFile.getFileFileName() != null) {
					String oldFilePath = config.getRealWebRootPath() + oldRelatedFile.getFileFileName();
					new File(oldFilePath).delete();
				}
			}
			
			int index = model.getFileFileName().indexOf('.');
			String picFileName;
			if (index > 0) {
				picFileName = model.getFileFileName().substring(index + 1);
			} else {
				picFileName = model.getFileFileName();
			}
			String destPicFileName = moveToDestFile(model.getFile(),
					clazz.getSimpleName() + "/", picFileName ,identity);
			model.setFileFileName(destPicFileName);
		}
	}
	
	private String moveToDestFile(File file, String destSubDir, String inputFileName, String dupliKey) {
		boolean success = false;
		String newName = null;
		inputFileName = inputFileName.substring(inputFileName.lastIndexOf('/') + 1);
		
//		while (!success) {
			if (dupliKey != null ){
				newName = config.getUploadDir() + destSubDir + dupliKey + '.' + inputFileName;
			} else {
				newName = config.getUploadDir() + destSubDir + inputFileName;
			}
			String destFileName = config.getRealSitePath() + newName;
			File destFile = new File(destFileName);
			destFile.getParentFile().mkdirs();
			success = file.renameTo(destFile);		// for duplicated file name, save it again
//		}
		return newName;
	}
}
